/*
 * @(#)QueryStringInjectInterceptor.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.interceptor.impl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.lucy.web.helper.ServletHelper;
import com.nhncorp.lucy.web.interceptor.AbstractInterceptor;
import com.nhncorp.usf.core.util.ServletRequestUtil;
import com.nhncorp.usf.core.util.StringUtil;
import com.nhncorp.usf.core.xwork.ActionInvocationHelper;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.PreResultListener;

/**
 * GET 방식 호출의 경우, {@link HttpServletRequest} 의 queryString 을 {@link Map} 에 삽입.
 * TOMCAT5 의 경우 Connector 에 useBodyEncodingForURI="true" 를 추가해주어야 한글이 깨지지 않는다.
 * GET 방식이 아닌 경우는 공백 문자를 queryString 값으로 사용한다. 추출된 queryString 은
 * {@code usf_querystring} 라는 이름으로 {@link Map} 에 저장된다. JSP 또는 Tempalte 에서 사용하기
 * 위해서는 ${usf_queryString} 를 이용한다.
 *
 * @author Web Platform Development Team
 */
@SuppressWarnings("serial")
public class QueryStringInjectInterceptor extends AbstractInterceptor {
    Log log = LogFactory.getLog(QueryStringInjectInterceptor.class);

    /**
     * @param actionInvocation the ActionInvocation
     * @return the interceptor result
     * @throws Exception for Exception
     */
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        actionInvocation.addPreResultListener(new PreResultListener() {
            
            public void beforeResult(ActionInvocation actionInvocation, String resultCode) {
                HttpServletRequest request = ServletHelper.getRequest(actionInvocation);
                String method = request.getMethod();
                String uri = request.getRequestURI();

                String queryString = null;

                if (method.equalsIgnoreCase("GET")) {
                    queryString = ServletRequestUtil.getQueryString(request);
                }

                queryString = StringUtil.isNotEmpty(queryString) ? queryString : "";
                Map<String, Object> dataMap = ActionInvocationHelper.getDataMap(actionInvocation);
                dataMap.put("usf_querystring", queryString);
                
                if (uri != null) {
                	dataMap.put("usf_uri", uri);
                }
                   
                log.debug("QueryString : " + queryString);
            }

        });

        return actionInvocation.invoke();
    }
}
